package com.example.a58;

import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import androidx.room.Room;
import androidx.room.RoomDatabase;

import java.io.File;
import java.util.List;

import Util.FileUtil;
import Util.SharedUtitl;
import database.Bookdatabse;
import database.ShoppingDBHelper;
import entity.GoodsInfo;

public class Myapplication extends Application {
    private static Myapplication mApp = null;
    public static Myapplication getInstance(){
        return mApp;
    }
    private Myapplication(){

    }
    //声明数据库对象
    private Bookdatabse bookdatabse = null;
    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        Log.e("TAG", "onCreate: 11111111111111111" );
        initDoodsInfo();
    }

    private void initDoodsInfo() {
        boolean isFist = SharedUtitl.getInstance(this).readBoolean("first",true);
        // 私有下载路径
        String  directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + File.separatorChar;

        if (isFist){
            //模拟图片下载
            List<GoodsInfo> list = GoodsInfo.getDefaultList();
            for (GoodsInfo info:list){
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), info.pic);
                String path = directory + info.id + ".jpg";
                //往存储卡存储商品图片
                FileUtil.saveImage(path,bitmap);
                //回收位图对象
                bitmap.recycle();
                info.picPath = path;
            }
            //打开数据库，把商品信息插入
            ShoppingDBHelper dbHelper = ShoppingDBHelper.getInstance(this);
            dbHelper.OpenWriteLink();
            dbHelper.insertGoodsInfo(list);
            dbHelper.closeLink();


            //把是否首次打开写入共享参数
            SharedUtitl.getInstance(this).writeBoolean("first",false);
        }
    }

    public Bookdatabse getBookDB(){
        if (bookdatabse == null){
            bookdatabse = Room.databaseBuilder(Myapplication.this,Bookdatabse.class,"book")
                    .addMigrations()//允许数据库发生迁移，数据库变更时，默认删除原数据库在创建新的数据，允许迁移就会保证数据不会丢失
                    .allowMainThreadQueries()//允许在朱线程操作数据库
                    .build();
        }
        return bookdatabse;
    }
}
